import { defineStore } from 'pinia'

export const useShippingRateStore = defineStore('shippingRate', {
    state: () => ({
        shippingRateData: {
            customer: {},
            selectedCustomers: [],
            freightForwarder: {
                air: {
                    business: []
                },
                fcl: {
                    business: []
                },
                lcl: {
                    business: []
                },
                originPortCharges: {
                    business: []
                },
                destinationPortCharges: {
                    business: []
                }
            },
            shipping: {},
            cfs: {},
            warehouse: {},
            transport: {},
            customs: {},
            metadata: {
                lastUpdated: "",
                version: "1.0"
            }
        },
        activeTopTab: 'forwarder',
        activeSubTab: 'air',
        serviceProviderSearchConfig: {
            url: 'http://gxmengshiqiye.net/jeecg-boot/dbsystem/dbuserandzd/list?bestop=0',
            keyField: 'posid',
            displayField: 'dbdatauser;posid;dbid',
            textshowField: 'dbid',
            delimiter: ';',
            token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MjUyNDMxNjAsInVzZXJuYW1lIjoiYWRtaW4ifQ.LOH1viCiq2sgo2Z5g_zP8jXpKl1qyBvThy9MGj6KYIA'
        },
        topTabs: ['forwarder', 'shipping', 'cfs', 'warehouse', 'transport', 'customs', 'summary'],
        topTabsDisplay: ['货代', '船公司及船舶', 'CFS', '仓库', '运输方式', '海关', '费率汇总'],
        subTabs: ['air', 'fcl', 'lcl', 'originPortCharges', 'destinationPortCharges'],
        subTabsDisplay: ['空运', 'FCL运费', 'LCL/FTL/TL/COU Freight', '起运港费用', '目的港费用']
    }),
    getters: {
        currentFreightForwarderData: (state) => {
            return state.shippingRateData.freightForwarder[state.activeSubTab]
        }
    },
    actions: {
        setActiveTopTab(tab) {
            this.activeTopTab = tab
        },
        setActiveSubTab(tab) {
            this.activeSubTab = tab
        },
        updateFreightForwarderData(newData) {
            console.log('Received newData in store:', newData);
            if (Array.isArray(newData.business)) {
                newData.business.forEach(businessRecord => {
                    if (this.validateFreightForwarderData(businessRecord.businessType, businessRecord)) {
                        console.log('Updating business record:', businessRecord.businessType, businessRecord);
                        const businessType = businessRecord.businessType;
                        if (!this.shippingRateData.freightForwarder[businessType]) {
                            this.shippingRateData.freightForwarder[businessType] = { business: [] };
                        }
                        const index = this.shippingRateData.freightForwarder[businessType].business.findIndex(b => b.id === businessRecord.id);
                        if (index !== -1) {
                            this.shippingRateData.freightForwarder[businessType].business[index] = businessRecord;
                        } else {
                            this.shippingRateData.freightForwarder[businessType].business.push(businessRecord);
                        }
                    } else {
                        console.error('Invalid data format for freight forwarder update', businessRecord.businessType, businessRecord);
                    }
                });
            } else {
                console.error('Invalid data format: expected an object with a business array', newData);
            }
        },


        updateNestedData(path, value) {
            const keys = path.split('.')
            let current = this.shippingRateData
            for (let i = 0; i < keys.length - 1; i++) {
                if (!current[keys[i]]) {
                    this.$patch((state) => {
                        state[keys[i]] = {}
                    })
                }
                current = current[keys[i]]
            }
            current[keys[keys.length - 1]] = value
        },
        handleSingleServiceProviderSelection(provider) {
            this.shippingRateData.customer = provider
        },
        handleMultiServiceProviderSelection(providers) {
            this.shippingRateData.selectedCustomers = providers
        },
        validateFreightForwarderData(businessType, data) {
            // 实现验证逻辑
            // 这里应该根据具体的数据结构来实现详细的验证
            if (!data || typeof data !== 'object') {
                return false
            }
            if (!Array.isArray(data.business)) {
                return false
            }
            // 可以添加更多的验证规则
            return true
        },
        addNewBusinessRecord(businessType) {
            const newRecord = this.createNewBusinessRecord(businessType)
            this.shippingRateData.freightForwarder[businessType].business.push(newRecord)
        },
        createNewBusinessRecord(businessType) {
            // 创建新的业务记录，根据业务类型返回不同的默认结构
            const baseRecord = {
                id: `${businessType}-${Date.now()}`,
                businessType: businessType,
                // 添加其他通用字段
            }

            switch(businessType) {
                case 'air':
                    return {
                        ...baseRecord,
                        // 添加空运特有的字段
                    }
                case 'fcl':
                    return {
                        ...baseRecord,
                        // 添加FCL特有的字段
                    }
                // 添加其他业务类型的case
                default:
                    return baseRecord
            }
        },
        updateBusinessRecord(businessType, recordId, updatedData) {
            const businessRecords = this.shippingRateData.freightForwarder[businessType].business
            const index = businessRecords.findIndex(record => record.id === recordId)
            if (index !== -1) {
                businessRecords[index] = { ...businessRecords[index], ...updatedData }
            } else {
                console.error(`Record with id ${recordId} not found in ${businessType} business`)
            }
        },
        deleteBusinessRecord(businessType, recordId) {
            const businessRecords = this.shippingRateData.freightForwarder[businessType].business
            const index = businessRecords.findIndex(record => record.id === recordId)
            if (index !== -1) {
                businessRecords.splice(index, 1)
            } else {
                console.error(`Record with id ${recordId} not found in ${businessType} business`)
            }
        }
    }
})
